package com.ddtj.demo1.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.ddtj.demo1.entity.User;
import com.ddtj.demo1.dao.UserJpa;
import com.ddtj.demo1.pojo.AjaxResult;
import com.ddtj.demo1.pojo.LoginUser;
import com.ddtj.demo1.service.TokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/loginUser")
public class LoginUserController {
    private final Logger log = LoggerFactory.getLogger(LoginUserController.class);
    @Autowired
    TokenService tokenService;
    @Autowired
    UserJpa userJpa;
    @PostMapping("/getToken")
    public String getToken(LoginUser loginUser){
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("loginUser",loginUser.getUsername());
        String token = tokenService.getToken(hashMap);
        return token;
    }
    @PostMapping("/verify")
    public DecodedJWT verify(String token){
        DecodedJWT decodedJWT = tokenService.verifyToken(token);
        String loginUser = decodedJWT.getClaim("loginUser").asString();
        return decodedJWT;
    }
    @GetMapping("/hello")
    public String hello(){
        return "Hello";
    }
    @PostMapping("/login")
    public AjaxResult login(LoginUser loginUser){
        User user = new User();
        user.setUsername(loginUser.getUsername());
        Example<User> userExample = Example.of(user);
        List<User> all = userJpa.findAll(userExample);
        if(null == all || all.size()<1){
            return AjaxResult.error("用户不存在");
        }
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        for (User user1 : all) {
            if(bCryptPasswordEncoder.matches(user1.getPassword(),user.getPassword())){
                HashMap<String, String> hashMap = new HashMap<>();
                hashMap.put("loginUser",loginUser.getUsername());
                String token = tokenService.getToken(hashMap);
                log.info("[{}]",loginUser.getUsername()+"登录成功");
                return AjaxResult.success("登录成功",token);
            }
        }
        return AjaxResult.error("密码错误");
    }
}
